package crud

import (
	"github.com/emicklei/go-restful"
	"github.com/jinzhu/gorm"
	"gitlab.com/adapt-karaoke-project/backend/config"
	"gitlab.com/adapt-karaoke-project/backend/model"
	"net/http"
	"strconv"
)

var stubSongService = []model.Song{
	model.Song{
		Model: gorm.Model{
			ID: config.IDSongStub,
		},
		Name:      "Virtual insanity",
		Original:  "Jamiroquai",
		Song:      strconv.Itoa(config.OIDMusicStub),
		Accompany: strconv.Itoa(config.OIDAccompanyStub),
		Cover:     strconv.Itoa(config.OIDCoverStub),
		Lyric:     strconv.Itoa(config.OIDLyricsStub),
		Midi:      strconv.Itoa(config.OIDMidiStub),
	},
}

func (cs *CrudService) initStubSongs() {
	for _, song := range stubSongService {
		cs.dbService.DB.Unscoped().Delete(&song)
		cs.dbService.DB.NewRecord(&song)
		cs.dbService.DB.Create(&song)
	}
}

func (cs *CrudService) GetAllSongs(req *restful.Request, resp *restful.Response) {
	songs := []model.Song{}
	cs.dbService.DB.Find(&songs)
	resp.WriteEntity(songs)
}

func (cs *CrudService) GetSongById(req *restful.Request, resp *restful.Response) {
	song_id_str := req.PathParameter("song-id")
	song_id, err := strconv.ParseUint(song_id_str, 10, 0)
	if err != nil {
		resp.WriteError(http.StatusBadRequest, err)
		return
	}
	var song model.Song
	cs.dbService.DB.First(&song, song_id)
	if song.ID == 0 {
		resp.WriteErrorString(http.StatusNotFound, "No such song")
		return
	}
	resp.WriteEntity(song)
}
